package com.geek.novel.view.edit

import android.content.Context
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.appcompat.widget.AppCompatEditText
import com.geek.novel.R
import com.geek.novel.utils.LogCatUtil


class ClearEditText: AppCompatEditText {

    private var iconDrawable:Drawable? = null

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        init(context)
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        init(context)
    }


    /**
     * 初始化UI组件
     */
    private fun init(context: Context) {
        iconDrawable = context.getDrawable(R.drawable.icon_clear)
        val w = lineHeight
        iconDrawable!!.setBounds(0, 0, w, w)
        this.setIconDrawable()
    }

    //设置删除图片
    private fun setIconDrawable() {
        val icon = if(text?.isNotEmpty() == true && isFocused) iconDrawable else null
        setCompoundDrawables(null,null, icon,null)
    }

    override fun onTextChanged(text: CharSequence?, start: Int, lengthBefore: Int, lengthAfter: Int) {
        super.onTextChanged(text, start, lengthBefore, lengthAfter)
        this.setIconDrawable()
    }

    //焦点改变监听
    override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect)
        this.setIconDrawable()
    }

    override fun performClick(): Boolean {
        LogCatUtil.d("???", "performClick")
        return super.performClick()
    }

    // 处理删除事件
    override fun onTouchEvent(event: MotionEvent): Boolean {
        event.let { e ->
            iconDrawable?.let {
                //判断触摸的区域是否在图标位置
                if(e.action == MotionEvent.ACTION_UP //当触摸抬起时
                    && e.x > width - it.intrinsicWidth
                    && e.x < width
                    && e.y > height / 2 - it.intrinsicHeight / 2
                    && e.y < height /2 + it.intrinsicHeight / 2
                ){
                    text?.clear()
                }
            }
        }
        //消除onTouchEvent()的警告
        performClick()
        return super.onTouchEvent(event)
    }

}